/*
 * Canvas Game Library
 * Module: AJAX
 * 
 * Copyright Chainsawrus Wreaks 2011
 * All rights reserved.
 */

/**
 * @fileOverview This is a AJAX module for the CGL library, this is imported when you want to use live
 * communication with the server during gameplay. I want to make this module as stable and rich as possible
 * to provide developers with a good toolbox of communication methods.
 */

/**
 * AJAX module namespace
 * @namespace CGL.ajax
 */

CGL.ajax = {
	_createXHR : function() {   
		try { return new XMLHttpRequest(); } catch(e) {}
	    try { return new ActiveXObject("Msxml2.XMLHTTP.6.0"); } catch (e) {}
	    try { return new ActiveXObject("Msxml2.XMLHTTP.3.0"); } catch (e) {}
	    try { return new ActiveXObject("Msxml2.XMLHTTP"); } 	  catch (e) {}
	    try { return new ActiveXObject("Microsoft.XMLHTTP"); }  catch (e) {}
							  	           
	    return null;
	},
	
	sendRequest : function(url, payload, callback) {
		var xhr = CGL.ajax._createXHR();
		if(xhr)
		{
			xhr.open("POST", url, false);
			xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
			xhr.onreadystatechange = function()
			{
				if (xhr.readyState == 4 && xhr.status == 200)
				{
					
					callback(xhr);
			  	}
			};
			xhr.send(payload);
		}
	},
	
	loadXML : function(src, callback) {
		var xhr = CGL.ajax._createXHR();
		if(xhr) {
			xhr.open("GET", src, false);
			xhr.onreadystatechange = function() {
				if(xhr.readyState == 4 && xhr.status == 200) {
					callback(xhr);
				}
			};
			xhr.send();
		}
	},
	
	loadJson : function(src, callback) {
		var xhr = CGL.ajax._createXHR();
		if(xhr)
		{
			xhr.open("GET", src, false);
			xhr.onreadystatechange = function()
			{
				if(xhr.readyState == 4 && xhr.status == 200)
				{
					callback(xhr);
				}
			};
			xhr.send(null);
		}
	},
	
	loadShader : function(src, callback, type) {
		var xhr = CGL.ajax._createXHR();
		if(xhr) {
			xhr.open("GET", src, false);
			xhr.onreadystatechange = function() {
				if(xhr.readyState == 4 && xhr.status == 200) {
					callback(xhr, type);
				}
			};
			xhr.send();
		}
	}
};



